package com.myjava.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project: datacenter-parent
 * @Author: chendongliang
 * @Date: 2018/8/22 18:49
 */
@Service
public class TranslateService implements ServletContextAware,InitializingBean {

    private final static Logger logger = LoggerFactory.getLogger(TranslateService.class);

    @Autowired
    DcSysDictionaryMapper dcSysDictionaryMapper;

    //上下文
    private ServletContext servletContext ;
    //字典缓存
    private static Map<String,String> dictMap = new HashMap();

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initDict();
    }

    /**
     * 字典加入缓存
     * */
    public void initDict(){
        List<DictResponse> list = dcSysDictionaryMapper.queryAll();
        if(list != null){
            list.forEach(dict->{dictMap.put(dict.getCode(), dict.getName());});
        }
        //加入到servlet上下文
        servletContext.setAttribute("DICT_MAP", dictMap);
        logger.info("-------------------------------------------------字典数据加入缓存成功--------------------------------------------------");
    }

    /***
     * 翻译list
     * @param list
     */
    public void translate(List<? extends Translateable > list){
        if(list == null){
            return;
        }
        list.forEach(obj->translate(obj));
    }

    /***
     * 翻译实例
     * @param obj
     */
    public void translate(Translateable obj){
        logger.debug("-------------------------------进入翻译------------------------------");
        if(obj == null){
            return ;
        }
        try {
            Field[] fields = obj.getClass().getDeclaredFields();
            if(fields != null && fields.length > 0){
                for(Field field:fields){
                    //判断属性是否有翻译注解并排除静态属性
                    if(field.isAnnotationPresent(TranslateDictCode.class) && !Modifier.isStatic(field.getModifiers())){
                        field.setAccessible(true);
                        String fileName = field.getName();
                        Object value = field.get(obj);
                        if(value != null){
                            if(value instanceof String) {
                                Field dictField = obj.getClass().getDeclaredField(fileName + "Name");
                                if (dictField.isAnnotationPresent(TranslateDictName.class)
                                        && !Modifier.isStatic(dictField.getModifiers())) {
                                    dictField.setAccessible(true);
                                    dictField.set(obj, dictMap.get(value));
                                }
                            }else if(value instanceof List){
                                List list = (List) value ;
                                if(list != null && list.size()>0 && list.get(0) instanceof Translateable){
                                    translate((List<Translateable>)list);
                                }
                            }else if(value instanceof Translateable){
                                translate((Translateable) value);
                            }
                        }
                    }
                }
            }
        } catch (NoSuchFieldException e) {
            logger.error("******************************被翻译属性无接收Name属性异常*************************{}",e);
        } catch (Exception e) {
            logger.error("******************************属性翻译处理异常*************************{}",e);
        }
    }

}
